//@ts-nocheck
import React from 'react';

function request(requestOpt){
  return new Promise((resolve, reject) => {
    setTimeout(()=>{
      resolve({
        users: ['小明', '小张']
      })
    },2000)
  });
}

const withRequest = ({requestOpt,filterData,actionList}) => (Target: any) => {
  class Proxy extends React.Component {
    constructor(props: any) {
      super(props);
      this.state = {}
    }

    async componentDidMount() {
      const res  = await request(requestOpt);
      const data = filterData(res);
      this.setState({
        ...filterData(data)
      });
    }

    render() {
      const actions = {};
      Object.keys(actionList).reduce((ret,actName) => {
        const action = () => actionList[actName](this.state, this.setState.bind(this));
        return ret[actName] = action
      },actions);

      return (
        <Target {...this.state} {...actions}/>
      );
    }
  }

  return Proxy;
};

export default withRequest({
  //some opt
  requestOpt: {
    url:'http://...'
    ,params: ''
    // ,...
  }
  ,filterData: json => {
    return {
      users: json.users
    }
  }
  ,actionList:{
    act1: (state,setState) => {
      setTimeout(() => {
        setState({...state,users:['张三','李四','王五']})
      },2000)
    }
  }
})(/** 无状态组件→*/(props)=>{
  if(props.users === undefined){
    return <div>loading ....</div>
  }

  return <ul>
    {props.users.map((x,i)=>{
      return <li key={i}>{x}</li>
    })}
    <button onClick={props.act1}>act1</button>
  </ul>
})
